package cn.zb.filter;

import cn.zb.common.util.Result;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.JSON;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description:网关全局过滤器配置示例  已注释
 * @Author:
 * @Date: 2024/11/22 18:47
 */
//@Component
@Order(1)
public class MyGlobalFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入全局过滤器");
        String path = exchange.getRequest().getPath().toString();
        // 访问的是登录时 放行
        if(path.endsWith("login")){
            return chain.filter(exchange);
        }
        // 获取请求对象
        String authority = exchange.getRequest().getHeaders().getFirst("authority");
        if(!StringUtils.isNotBlank(authority)){
            ServerHttpResponse response = exchange.getResponse();
            // 设置状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 设置响应数据
            String s = JSON.toJSONString(Result.fail("请先登录"));
            DataBuffer db = response.bufferFactory().wrap(s.getBytes());

            return response.writeWith(Mono.just(db));
        }
        return chain.filter(exchange);
    }


}
